<?php
namespace app\taobao\controller;

use Curl\Curl;
use think\Db;
use think\image\Exception;

/**
 * 这里的功能由python接手了 这里的没用了
 * 甩手掌柜的接口数据都弄到这里
 * Class Zhanggui
 * @package app\taobao\controller
 *
 */
class Zhanggui{

    /**
     * tn是table name的意思  其他的接口中都带有表名 这些都是表名字    sys_sysSort  sys_syspropertyvalue  sys_sysproperty sys_sysproperty
     * @var array
     */
    protected $soapAction = [
        'DownloadRelSortIdsBySysSortId'=>[
            'param'=>'<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><DownloadRelSortIdsBySysSortId xmlns="http://www.cogentsoft.com.cn/"><loginSequence>#loginSequence#</loginSequence><sysSortId>#sysSortId#</sysSortId></DownloadRelSortIdsBySysSortId></soap:Body></soap:Envelope>',
            'soapAction'=>'http://www.cogentsoft.com.cn/DownloadRelSortIdsBySysSortId'
        ],
        'DownloadPropertyInfoBySysSortId'=> [
            /*'param'=>'<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><DownloadPropertyInfoBySysSortId xmlns="http://www.cogentsoft.com.cn/"><loginSequence>#loginSequence#</loginSequence><sysSortId>#sysSortId#</sysSortId></DownloadPropertyInfoBySysSortId></soap:Body></soap:Envelope>',*/
            'param'=>'<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><DownloadPropertyInfoBySysSortId xmlns="http://www.cogentsoft.com.cn/"><loginSequence>#loginSequence#</loginSequence><sysSortId>#sysSortId#</sysSortId></DownloadPropertyInfoBySysSortId></soap12:Body></soap12:Envelope>',
            'soapAction'=>'http://www.cogentsoft.com.cn/DownloadPropertyInfoBySysSortId'
        ],
        'DownloadBasicData'=>[
            'param'=>'<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><DownloadBasicData xmlns="http://www.cogentsoft.com.cn/"><loginSequence>#loginSequence#</loginSequence><tn>#tn#</tn></DownloadBasicData></soap12:Body></soap12:Envelope>',
            /*'param'=>'<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><DownloadBasicData xmlns="http://www.cogentsoft.com.cn/"><loginSequence>#loginSequence#</loginSequence><tn>#tn#</tn></DownloadBasicData></soap:Body></soap:Envelope>',*/
            'soapAction'=>'http://www.cogentsoft.com.cn/DownloadBasicData'
         ],
        'UpdateBaseData'=>[
            'param'=>'<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><UpdateBaseData xmlns="http://www.cogentsoft.com.cn/"><loginSequence>#loginSequence#</loginSequence><tn>#tn#</tn><lastUpdateTime>#lastUpdateTime#</lastUpdateTime></UpdateBaseData></soap:Body></soap:Envelope>',
            'soapAction'=>'http://www.cogentsoft.com.cn/UpdateBaseData'
        ]
    ];



    protected $allReplaceData= [
        '#loginSequence#'=>'04c4d4ff-bf7c-45c3-b751-d556463fbe81',
        '#tn#'=>'sys_sysSort',
        '#sysSortId#'=>'182255',
        '#lastUpdateTime#'=>'2007-07-07 00:00:00'
    ];


    private function getParamByAction($action = ''){
        $data = $this->soapAction[$action];

        foreach($this->allReplaceData as $key => $val ){
            $data['param'] = str_replace($key,$val,$data['param']);
        }
        return $data;
    }

    public function soap(){
        $prepare  = $this->getParamByAction("DownloadPropertyInfoBySysSortId");
        $url = "http://service.shuaishou.com/service.asmx";

        $ch = curl_init (); //initiate the curl session
        curl_setopt ( $ch, CURLOPT_URL, $url ); //set to url to post to
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); // return data in a variable
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $prepare['param'] ); // post the xml
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 ); // set timeout in seconds
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
        $header = array ("Content-Type: text/xml" );
        $header [] = "Content-Length: ".strlen($prepare['param']);

        $header [] = 'SOAPAction: "' . $prepare['soapAction'] . '"';
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        $xmlResponse = curl_exec ( $ch );
        curl_close ( $ch );
        echo '1234';
        echo $xmlResponse;exit;
        $myfile = fopen("sys_syspropertyvalue.txt", "w");
        fwrite($myfile, $xmlResponse);
        fclose($myfile);
    }


    /**
     * 状态机处理大文件 本函数使命完成
     */
    public function parseSysSort(){
        exit;
        set_time_limit(0);
        $fs = fopen("sys_sysSort.txt",'r');
        $position = ftell($fs);
        $index = 0;
        $state = 0;
        $tmpStr = '';
        $fileIndex = 0;
        while(!feof($fs)){
            $char = fread($fs,1);
            //echo $char;

            switch($state){
                case 0:
                    if($char == "[") $state = 1;
                    else $state = 0;
                    break;
                case 1:
                    if($char == "&"){
                        $state = 2;
                        $tmpStr .= $char;
                    } elseif($char == ";"){
                        $state = 3;
                    }else{
                        $tmpStr .= $char;
                        $state = 1;
                    }
                    break;
                case 2:
                    if($char == ';'){
                        $state = 3;
                    }elseif($char == 'g'){
                        $state = 4;
                        $tmpStr .= $char;
                    }else{
                        $tmpStr .= $char;
                    }
                    break;
                case 3:
                    //echo $tmpStr.'------<br />';
                    $fileNameIndex = floor($fileIndex/10000);
                    file_put_contents("data_".$fileNameIndex.'.txt',$tmpStr."\n",FILE_APPEND);
                    $fileIndex++;
                    $tmpStr = $char;
                    $state = 1;
                    break;
                case 4:
                    if($char == 't'){
                        $state = 5;
                        $tmpStr .= $char;
                    }elseif($char == ';'){
                        $state = 3;
                    }else{
                        $state = 1;
                        $tmpStr .= $char;
                    }
                    break;
                case 5:
                    $state = 1;
                    $tmpStr.=$char;
                    break;
            }

            $index++;

        }




    }

    /**path|
     * indexnum|
     * remark|
     * ver|
     * isnewsellpro|
     * parentkey|
     * modifytime|
     * del|
     * name|
     * sizegrouptype|
     * sysid|
     * isnew|
     * hassellinfo|
     * id|
     * isconfirm|
     * parentid|
     * levels|
     * keys
     * 本函数使命完成
     */
    public function parseSysSortData(){
        exit;
        set_time_limit(0);
        $fileIndex = 0;
        try{
            while(true){
                echo $fileIndex.'<br />';
                $handle = @fopen("data_".$fileIndex.".txt", "r");
                if ($handle) {
                    $index = 0;
                    while (!feof($handle)) {
                        $buffer = fgets($handle, 4096);
                        $row = (explode("|",$buffer));
                        $data = [
                            'path'=>@$row[0],
                            'indexnum'=>@$row[1],
                            'remark'=>@$row[2],
                            'ver'=>@$row[3],
                            'isnewsellpro'=>@$row[4],
                            'parentkey'=>@$row[5],
                            'modifytime'=>@$row[6],
                            'del'=>@$row[7],
                            'name'=>@$row[8],
                            'sizegrouptype'=>@$row[9],
                            'sysid'=>@$row[10],
                            'isnew'=>@$row[11],
                            'hassellinfo'=>@$row[12],
                            'id'=>@$row[13],
                            'isconfirm'=>@$row[14],
                            'parentid'=>@$row[15],
                            'levels'=>@$row[16],
                            'keys'=>@$row[17],
                        ];
                        Db::table("sys_syssort")->insert($data);
                    }
                    fclose($handle);
                    $fileIndex++;
                }else{
                    break;
                }
            }
        }catch (Exception $e){
            echo $e->getMessage();
        }



    }

    public function runTask(){
        set_time_limit(0);
        while(true){

            $curl = new Curl();
            $res = $curl->get("http://taobao.yangjifang.com/taobao/Zhanggui/parseSysPropertyFile");
            /*if($res->response == 'SUCCESS'){

            }*/
        }
    }

    public function parseSysPropertyFile(){
            $result = Db::table('sys_property_file')->where('isprocess','null')->order('id asc')->find();
            //if(!$result) continue;
            if(!$result) exit;
            $fileContent = htmlspecialchars_decode($result['content']);

            $res = preg_match_all('/<Data\s*tableName=\"(.*?)\"\s*fieldName=\"(.*?)"\s*><!\[CDATA\[(.*?)\]\]><\/Data>/', $fileContent, $match);

            if ($res) {
                $tables = $match[1];
                $columns = $match[2];
                $tableValues = $match[3];

                foreach ($tables as $key => $val) {
                    $this->parseAndInsertData($val, $columns[$key], $tableValues[$key]);
                }
            }

            Db::table('sys_property_file')->where('id',$result['id'])->update(['isprocess'=>1]);
            return 'SUCCESS';
    }


    public function parseAndInsertData($tableName,$column,$value){
        $result = explode(";",$value);
        $columns= explode("|",$column);
        if($result){
            foreach($result as $key => $val ){
                $records = explode("|",$val);
                $data = [];
                foreach($columns as $k => $v){
                    $data[$v] = $records[$k];
                }
                Db::table($tableName)->insert($data);
            }
        }
    }

    /**
     * 测试php 如何清理内存
     */
    public function memory(){
        set_time_limit(0);
        $loop = 1;
        $start = memory_get_usage();
        $count = 0;
        while(true){
            $count++;
            $result = Db::table("cats")->order('id asc')->find();
            Db::free();
            Db::close();
            if($count >= $loop) {
                $end = memory_get_usage();
                $use = $end-$start;
                echo "start:".$start."<br />end:".$end."<br />use:".$use;
                exit;
            }

        }

    }


    /**
     * categoryId":"50020835
     * 获取属性的id
     * "品牌":"祥礼"
     */
    public function getPropertyByPropertyName($categoryId = '50020835',$property='品牌',$propertyValue = '祥礼'){

    }

}